package com.example.vaultmysql.repository;

import com.example.vaultmysql.entity.TestExecution;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 测试执行Repository
 * 
 * @author System
 * @version 1.0.0
 */
@Repository
public interface TestExecutionRepository extends JpaRepository<TestExecution, String> {

    /**
     * 根据状态查找测试执行记录
     */
    List<TestExecution> findByStatus(TestExecution.TestStatus status);

    /**
     * 查找正在运行的测试
     */
    List<TestExecution> findByStatusIn(List<TestExecution.TestStatus> statuses);

    /**
     * 根据创建者查找测试记录
     */
    List<TestExecution> findByCreatedByOrderByCreatedAtDesc(String createdBy);

    /**
     * 查找指定时间范围内的测试记录
     */
    @Query("SELECT t FROM TestExecution t WHERE t.createdAt BETWEEN :startTime AND :endTime ORDER BY t.createdAt DESC")
    List<TestExecution> findByCreatedAtBetween(@Param("startTime") LocalDateTime startTime, 
                                              @Param("endTime") LocalDateTime endTime);

    /**
     * 查找最近的测试记录
     */
    @Query("SELECT t FROM TestExecution t ORDER BY t.createdAt DESC")
    List<TestExecution> findRecentTests();

    /**
     * 统计各状态的测试数量
     */
    @Query("SELECT t.status, COUNT(t) FROM TestExecution t GROUP BY t.status")
    List<Object[]> countByStatus();

    /**
     * 查找当前正在运行的测试
     */
    @Query("SELECT t FROM TestExecution t WHERE t.status = 'RUNNING'")
    List<TestExecution> findRunningTests();

    /**
     * 检查是否有正在运行的测试
     */
    @Query("SELECT COUNT(t) > 0 FROM TestExecution t WHERE t.status = 'RUNNING'")
    boolean hasRunningTests();
}